import 'package:flutter/material.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/input_option.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/patient.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

/// 新增患者界面，或者患者信息编辑界面，展示或者信息
class PatientAddPage extends StatefulWidget {
  static const String routeName = '/patient_add';

  /// 传入患者id，获取患者信息进行数据展示。
  final String id;

  const PatientAddPage({Key key, this.id}) : super(key: key);

  @override
  _PatientAddPageState createState() => _PatientAddPageState();
}

class _PatientAddPageState extends State<PatientAddPage> {
  TextEditingController _nameController = TextEditingController();
  TextEditingController _ageController = TextEditingController();
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _cardController = TextEditingController();
  TextEditingController _locationController = TextEditingController();
  TextEditingController _emailController = TextEditingController();
  TextEditingController _addressController = TextEditingController();
  int _genderIndex = -1;
  int _marryIndex = -1;
  List<String> _marryData = ['否', '是'];

  @override
  void initState() {
    super.initState();
    if (widget.id != null) {
      _fetchData();
    }
  }

  @override
  void dispose() {
    super.dispose();
    _nameController.dispose();
    _ageController.dispose();
    _phoneController.dispose();
    _cardController.dispose();
    _locationController.dispose();
    _emailController.dispose();
    _addressController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String title;
    if (widget.id != null) {
      title = '患者详情';
    } else {
      title = '新增患者';
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: ListView(
        padding: EdgeInsets.only(top: 10, bottom: 100),
        children: [
          PrimaryLabel('患者信息'),
          InputOption(
            label: '姓名：',
            hintText: '请输入患者姓名',
            controller: _nameController,
          ),
          TextOption(
            label: '性别：',
            secondText: _genderIndex == -1
                ? '请选择患者性别'
                : Constants.genderData[_genderIndex],
            secondTextColor: _genderIndex == -1 ? Colors.grey : Colors.black,
            onTap: () {
              CommonUtils.hideKeyboard(context);
              DialogUtils.showSelectOptionDialog(
                      context, '性别选择', Constants.genderData)
                  .then((value) {
                if (value != null) {
                  setState(() {
                    _genderIndex = value;
                  });
                }
              });
            },
          ),
          InputOption(
            label: '年龄：',
            hintText: '请输入患者年龄',
            controller: _ageController,
            type: InputType.age,
          ),
          InputOption(
            type: InputType.phone,
            label: '手机号码：',
            hintText: '请输入患者手机号码',
            controller: _phoneController,
          ),
          InputOption(
            type: InputType.card,
            label: '身份证号：',
            hintText: '请输入患者身份证号码',
            controller: _cardController,
          ),
          CustomDivider(),
          PrimaryLabel('其他信息'),
          TextOption(
            label: '婚否',
            secondText: _marryIndex == -1 ? '请选择是否婚配' : _marryData[_marryIndex],
            secondTextColor: _marryIndex == -1 ? Colors.grey : Colors.black,
            onTap: () {
              CommonUtils.hideKeyboard(context);
              DialogUtils.showSelectOptionDialog(context, '是否婚配', _marryData)
                  .then((value) {
                if (value != null) {
                  setState(() {
                    _marryIndex = value;
                  });
                }
              });
            },
          ),
          InputOption(
            label: '籍贯：',
            hintText: '请输入患者籍贯',
            controller: _locationController,
          ),
          InputOption(
            label: '邮箱：',
            hintText: '请输入患者邮箱',
            controller: _emailController,
          ),
          InputOption(
            label: '现居地址：',
            hintText: '请输入患者现居地址',
            controller: _addressController,
          ),
          PrimaryButton('提交', onPressed: _create),
        ],
      ),
    );
  }

  void _create() async {
    CommonUtils.hideKeyboard(context);
    String name = _nameController.text.trim();
    String age = _ageController.text.trim();
    String phone = _phoneController.text.trim();
    String card = _cardController.text.trim();
    String location = _locationController.text.trim();
    String email = _emailController.text.trim();
    String address = _addressController.text.trim();
    if (name.isEmpty) {
      ToastUtil.show('请输入姓名', context);
      return;
    }
    if (_genderIndex == -1) {
      ToastUtil.show('请选择性别', context);
      return;
    }
    if (age.isEmpty) {
      ToastUtil.show('请输入年龄', context);
      return;
    }
    if (phone.isEmpty) {
      ToastUtil.show('请输入手机号码', context);
      return;
    }
    if (card.isEmpty) {
      ToastUtil.show('请输入身份证号', context);
      return;
    }
    if (_marryIndex == -1) {
      ToastUtil.show('请选择婚否', context);
      return;
    }
    if (location.isEmpty) {
      ToastUtil.show('请输入籍贯', context);
      return;
    }
    if (email.isEmpty) {
      ToastUtil.show('请输入邮箱', context);
      return;
    }
    if (address.isEmpty) {
      ToastUtil.show('请输入现居地址', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var params = {
      "fullname": name, //姓名
      "sex": _genderIndex, //性别
      "age": age, //年龄
      "maritalType": "$_marryIndex", //婚否 0 否 1 是
      "nativePlace": location, //籍贯
      "cellphone": phone, //手机号
      "idcard": card, //身份证号
      "email": email, //邮箱
      "address": address, //地址
      "attachDoctorId": SPUtils.getUser().id //医生account id
    };
    if (widget.id != null) {
      params['id'] = widget.id;
    }
    var data = await XHttp.postJson(
        widget.id == null ? Urls.PATIENT_ADD : Urls.PATIENT_UPDATE, params);
    Navigator.pop(context);
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 1) {
        ToastUtil.show('操作成功', context);
        Navigator.pop(context, true);
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _fetchData() async {
    var data = await XHttp.postJson(sprintf(Urls.PATIENT_DETAIL, [widget.id]));
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data as Map<String, dynamic>);
      if (response.code == 1 && mounted) {
        var bean = Patient.fromJson(response.data);
        setState(() {
          _nameController.text = bean.fullname;
          _genderIndex =
              CommonUtils.isNumeric(bean.sex) ? int.parse(bean.sex) : -1;
          _ageController.text = bean.age.toString();
          _phoneController.text = bean.cellphone;
          _cardController.text = bean.idcard;
          _marryIndex = _marryData.indexOf(bean.maritalTypeValue);
          _addressController.text = bean.address;
          _locationController.text = bean.nativePlace;
          _emailController.text = bean.email;
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
